package com.cheer.controller;

import com.cheer.common.Result;
import com.cheer.dto.OaLearnEntryQueryDTO;
import com.cheer.entity.OaLearnEntity;
import com.cheer.enums.OaIntegralRuleEnum;
import com.cheer.exception.ServiceException;
import com.cheer.job.OaLearnTask;
import com.cheer.param.OrgRateParam;
import com.cheer.security.UserInfoHolder;
import com.cheer.service.*;
import com.cheer.vo.OaAdminHomeVO;
import com.cheer.vo.OaLearnEntryCompareVO;
import com.cheer.vo.OaLearnEntryVO;
import com.cheer.vo.RateVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

/**
 * @author cheer
 */
@RestController
@RequestMapping("/home")
@Api(tags = "用户登录首页" )
@Slf4j
public class OaHomeController implements ApplicationListener<ApplicationReadyEvent> {

    @Autowired
    private OaLearnService oaLearnService;

    @Autowired
    private OaLearnEntryService oaLearnEntryService;

    @Autowired
    private OaAsyncService oaAsyncService;

    @Autowired
    private UserInfoHolder userInfoHolder;

    private OaAdminHomeVO adminHomeVO = new OaAdminHomeVO();

    @Override
    public void onApplicationEvent(ApplicationReadyEvent event) {
        log.info("OaHomeController start... 应用程序已完成初始化并已经准备好提供服务");
        new Thread(() -> {
            while (true) {
                try {
                    OaLearnEntity learn = oaLearnService.getFirst();

                    Future<Integer> future1 = oaAsyncService.countUser();
                    Future<Integer> future2 = oaAsyncService.countByType(OaIntegralRuleEnum.ARTICLE.getCode());
                    Future<Integer> future3 = oaAsyncService.countByType(OaIntegralRuleEnum.VIDEO.getCode());

                    Future<Integer> future4 = oaAsyncService.countByLearnId(learn.getId());
                    Future<Integer> future5 = oaAsyncService.countByTypeAndItem(OaIntegralRuleEnum.CURRENT.getCode(), learn.getId());
                    Future<Integer> future6 = oaAsyncService.countByTypeAndTime(OaIntegralRuleEnum.LOGIN.getCode(), Integer.valueOf(learn.getStartTime()));

                    adminHomeVO.setTotal(future1.get())
                            .setArticle(future2.get())
                            .setVideo(future3.get())
                            .setEntry(future4.get())
                            .setStudy(future5.get())
                            .setLogin(future6.get());

                } catch (Exception e) {
                    log.error(e.getMessage(), e);
                }

                try {
                    Thread.sleep(30000);
                } catch (InterruptedException e) {
                    log.error(e.getMessage(), e);
                }
            }
        }).start();
    }

    @ApiOperation("首页信息")
    @GetMapping("/info")
    @PreAuthorize("@permissionValidator.isAdmin()")
    public Result<OaAdminHomeVO> info() {
        return Result.success(adminHomeVO);
    }


    @ApiOperation("查询本期排名")
    @GetMapping("/entry")
    public Result<List<OaLearnEntryVO>> list(Integer pid) {
        if (pid == null) {
            pid = userInfoHolder.getAdmin().getPid();
        }
        return Result.success(oaLearnEntryService.listHome(pid));
    }

    @ApiOperation("机构排名")
    @PostMapping("org/rate")
    public Result orgRate(@RequestBody @Valid OrgRateParam orgRateParam) {
        if (orgRateParam.getPid() == null) {
            orgRateParam.setPid(userInfoHolder.getAdmin().getPid());
        }
        RateVO vos = null;
        try {
            vos = oaLearnEntryService.orgRate(orgRateParam.getStartDate(),
                    orgRateParam.getEndDate(), orgRateParam.getLearnId(), orgRateParam.getPid());
        } catch (Exception e) {
            return Result.success(new ArrayList<>());
        }
        return Result.success(vos);
    }

    @ApiOperation("县排名 TODO")
    @PostMapping("/prefecture/rate")
    public Result prefectureRate(@RequestBody @Valid OrgRateParam orgRateParam) {
        RateVO vos = null;
        try {
            vos = oaLearnEntryService.prefectureRate(orgRateParam.getStartDate(),
                orgRateParam.getEndDate(), orgRateParam.getLearnId());
        } catch (Exception e) {
            return Result.success(new ArrayList<>());
        }
        return Result.success(vos);
    }


    @ApiOperation("高校排名 TODO")
    @PostMapping("/school/rate")
    public Result schoolRate(@RequestBody @Valid OrgRateParam orgRateParam) {

        RateVO vos = null;
        try {
            vos = oaLearnEntryService.schoolRate( orgRateParam.getStartDate(),
                    orgRateParam.getEndDate(), orgRateParam.getType(), orgRateParam.getLearnId());
        } catch (Exception e) {
            return Result.success(new ArrayList<>());
        }
        return Result.success(vos);
    }

    @ApiOperation("下载高校排名 TODO")
    @PostMapping("/entry/schoolDownload")
    public Result schoolDownload(@RequestBody @Valid OrgRateParam orgRateParam) {

        try {
            oaLearnEntryService.schoolDownload(orgRateParam.getStartDate(),
                    orgRateParam.getEndDate(), orgRateParam.getType(), orgRateParam.getLearnId());
            return Result.success();
        } catch (Exception e) {
            return Result.success(e.getMessage());
        }
    }

    @ApiOperation("下载机关排名 TODO")
    @PostMapping("/entry/download")
    public Result orgDownload(@RequestBody @Valid OrgRateParam orgRateParam) {
        Integer pid = orgRateParam.getPid();
        if (pid == null) {
            pid = userInfoHolder.getAdmin().getPid();
        }
        try {
            oaLearnEntryService.download(orgRateParam.getStartDate(),
                    orgRateParam.getEndDate(),  pid, orgRateParam.getLearnId());
        } catch (Exception e) {
            return Result.success(e.getMessage());
        }
        return Result.success();
    }

    @ApiOperation("下载县排名 TODO")
    @PostMapping("/prefecture/download")
    public Result prefectureDownload(@RequestBody @Valid OrgRateParam orgRateParam) {
        try {
            oaLearnEntryService.prefectureDownload(orgRateParam.getStartDate(),
                    orgRateParam.getEndDate(), orgRateParam.getLearnId());
        } catch (Exception e) {
            return Result.success(e.getMessage());
        }
        return Result.success();
    }

}
